import Vue from "vue";
import router from "./router";
import store from "./store";
import NProgress from "nprogress"; // progress bar 进度条
import "@/components/NProgress/nprogress.less"; // progress bar custom style
// import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from "@/utils/domUtil";
import { ACCESS_TOKEN } from "@/store/mutation-types";
// import {Modal}  from 'ant-design-vue';

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = store.getters.whiteList;
// const whiteList = ["login", "register", "registerResult"]; // no redirect whitelist
const defaultRoutePath = "/dashboard/workplace";
//vue-router 一共给我们提供了三大类钩子函数来实现路由守卫：
//1、全局钩子函数（beforeEach、afterEach)
//2、路由独享的钩子函数（beforeEnter）
//3、组件内钩子函数（beforeRouterEnter、beforeRouterUpdate、beforeRouterLeave）
router.beforeEach((to, from, next) => {
    // console.log("进入拦截器");
    // console.log("to:", to, "from:", from);
    NProgress.start(); // start progress bar
    to.meta &&
        typeof to.meta.title !== "undefined" &&
        setDocumentTitle(`${to.meta.title} - ${domTitle}`);
    const token = Vue.ls.get(ACCESS_TOKEN);

    // antd.Modal.destroyAll();
    //跳转路由 强行删除 所有的 弹窗
    let ModalRootHtmls = document.getElementsByClassName('ant-modal-root');
    ModalRootHtmls && ModalRootHtmls.forEach(element => {
        element.remove();
    });
    // 如果是当前页面处于编辑状态
    if (store.getters.isCurrentPageOnEdit) {
        let message = "当前数据未保存,离开后数据可能会丢失，是否离开？";
        let okText = "离开";
        let cancelText = "留下";
        antd.Modal.confirm({
            title: '提示',
            content: message,
            okText,
            cancelText,
            onOk () {
                console.log("离开next()")
                //设置全局状态：当前页数 是否处于编辑状态
                store.commit('SET_CURRENT_PAGE_ON_EDIT', false);
                next();
            },
            onCancel () {
                console.log("留下next(false)")
                next(false);
            },
        });
        NProgress.done();
        return false;
    }

    if (token) {
        /* has token */
        // if (to.path === "/user/login") {
        //   next({ path: defaultRoutePath });
        //   NProgress.done();
        // }else
        if (whiteList.includes(to.name)) {
            // 在免登录白名单，直接进入
            next();
        }
        else {
            //   console.log("store.user.name",Object.keys(store.getters.userInfo).length)
            if (!Object.keys(store.getters.userInfo).length) {
                store.dispatch("GetInfo").then(res => {
                    // console.log("获取用户信息后，权限拦截处理", res);
                    store.dispatch("GenerateRoutes", { token }).then(() => {
                        // 根据roles权限生成可访问的路由表
                        // 动态添加可访问路由表
                        router.addRoutes(store.getters.addRouters);
                        // console.log("router", router);
                        // 请求带有 redirect 重定向时，登录自动重定向到该地址
                        const redirect = decodeURIComponent(
                            from.query.redirect || to.path
                        );
                        // console.log("重定向redirect->",redirect)
                        if (to.path === redirect) {
                            // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                            next({ ...to, replace: true });
                        } else {
                            // 跳转到目的路由
                            // console.log("store.getters.menusMap.get(redirect)",store.getters.menusMap,store.getters.menusMap.get(redirect))
                            if (from.path == '/user/login' && !store.getters.menusMap.get(redirect)) {
                                next({ path: defaultRoutePath });
                            } else {
                                next({ path: redirect });
                            }
                        }
                    });
                }).catch((e) => {
                    // console.log("请求用户信息失败，请重试1111");
                    // if(e.response.status == 500){
                    //   notification.error({
                    //     message: '错误',
                    //     description: '请求用户信息失败，请重试'
                    //   })
                    // }

                    store.dispatch("Logout").then(() => {
                        next({ path: "/user/login", query: { redirect: to.fullPath } });
                    });
                });
            } else {
                next();
            }
        }
    } else {
        console.log("没有token");
        if (whiteList.includes(to.name)) {
            // 在免登录白名单，直接进入
            next();
        } else {
            next({ path: "/user/login", query: { redirect: to.fullPath } });
            NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
        }
    }
});

router.afterEach((to, from, next) => {
    if (to.name && !whiteList.includes(to.name) && to.path != defaultRoutePath) {
        // console.log("进入下一个组件",to,from,next)
        store.commit("SET_TAB_MAP", to);
    }
    NProgress.done(); // finish progress bar
});
